<template>
  <div class="app-container">
    <div class="filter-container">
      <span v-if="roles!='plain'" >
    <!--      <el-input size="small" v-model.trim="listQuery.submit_name" placeholder="姓名" style="width: 150px;" class="filter-item" @keyup.enter.native="handleFilter" />-->
          <el-select size="small" v-model="listQuery.admin_id" placeholder="创建者" clearable style="width: 300px;" class="filter-item">
            <el-option v-for="item in admin_data" :key="item.admin_id" :label="item.admin_name" :value="item.admin_id" />
          </el-select>
          <el-input size="small" v-model="listQuery.phone" placeholder="联系方式" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
          <el-date-picker
            class="filter-item"
          size="small"
          v-model.trim="listQuery.date1"
          type="datetime"
          placeholder="选择创建起始日期"
          value-format="yyyy-MM-dd HH:mm:ss">
        </el-date-picker>
          <el-date-picker
            class="filter-item"
            size="small"
            v-model.trim="listQuery.date2"
            type="datetime"
            placeholder="选择创建结束日期"
            value-format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker>
          <el-button size="small" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter" style="margin-left: 20px">
            查询
          </el-button>
      </span>
<!--      <el-button size="small" v-if="roles=='admin'" :loading="downloadLoading" class="filter-item" type="danger" icon="el-icon-delete" @click="handleAllDelete">-->
<!--        删除全部数据-->
<!--      </el-button>-->
      <el-button size="small" class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        新增
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column label="创建者" width="150">
        <template slot-scope="scope">
          {{ scope.row.admin_name }}
        </template>
      </el-table-column>
      <el-table-column label="导航栏标题"  width="300">
        <template slot-scope="scope">
          {{ scope.row.forms_title }}
        </template>
      </el-table-column>
      <el-table-column label="程序二维码"  align="center" width="110">
        <template slot-scope="scope">
          <viewer>
            <img :src="scope.row.url_img" width="100" height="100" alt="">
          </viewer>
        </template>
      </el-table-column>
      <el-table-column label="开始时间">
        <template slot-scope="scope">
          {{ scope.row.forms_start_time }}
        </template>
      </el-table-column>
      <el-table-column label="结束时间">
        <template slot-scope="scope">
          {{ scope.row.forms_end_time }}
        </template>
      </el-table-column>
      <el-table-column label="程序url" width="400">
        <template slot-scope="scope">
          {{ scope.row.url }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="created_at" label="创建时间" width="200">
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span>{{ scope.row.forms_create_time }}</span>
        </template>
      </el-table-column>


      <el-table-column fixed="right" label="操作" align="center" width="150" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-if="roles!='plain'" style="margin-bottom: 10px" size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>

          <el-button type="primary" size="mini" @click="lookDataOpen(row)">
            查看数据
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="fetchData" />
    <el-dialog :fullscreen="true" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :before-close="dialogFormClose" >
      <div v-if="draggable">
        <draggable-index3  ref="forms" :arr2="arr2" @draggableVal = "handleData" :getFormDataItem2="formDataItem2" :type="dialogStatus"></draggable-index3>
      </div>
    </el-dialog>
    <el-dialog
      :title="lookDataTitle"
      :visible.sync="lookDataStatus"
      :fullscreen="true"
      :before-close="lookDataCloseF"
      center>
      <appDataList :forms_id="forms_id" :table_name="lookDataTitle"></appDataList>
    </el-dialog>
  </div>
</template>
<style>
/*.filter-container{*/
/*  padding-bottom: 20px;*/
/*}*/
.filter-item{
  margin: 5px 5px;
  margin-bottom: 20px;
}
.head_qrcode{
  /*width: 375px;*/
  /*height: 1000px;*/
  width: 340px;
  height: 430px;
  border: 1px solid slategray;
  /*background-size: 100% 100%;*/
}
.f-title{
  display: flex;
  padding: 0 5%;
}
.f-save{
  width: 30%;
  font-weight: bold;
  font-size: 30px;
}
.el-dialog__headerbtn .el-dialog__close{
  font-size: 50px;
  color: #FF0000;
}
</style>
<script>
import {getForms, createForms, updateForms, delForms} from '@/api/application'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { getToken } from '@/utils/auth'
import Tinymce from '@/components/Tinymce'
import {updateAdmin} from "@/api/admin";
import {mapGetters} from "vuex";
import draggableIndex3 from '@/views/draggable/index.vue'
import appDataList from "@/views/application/appDataList";
import QRCode from 'qrcode';
export default {
  filters: {
    sexFilter(sex) {
      const sexMap = {
        男: 'success',
        女: 'danger'
      }
      return sexMap[sex]
    },
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  computed:{
    tokenFig(){
      return {token:getToken()}
    },
    ...mapGetters([
      'roles',
      'name'
    ])
  },
  data() {
    return {
      forms_id:'',
      lookDataTitle:'',
      lookDataStatus:false,
      draggable:false,
      formDataItem2:{},
      arr2:[],
      qrcode:'',
      admin_data:'',
      downloadLoading:false,
      table_name:'用户数据导出',
      importanceOptions:['男','女'],
      total: 0,
      listQuery: {
        page: 1,
        limit: 10,
        admin_id: undefined,
        phone: undefined,
        date1:undefined,
        date2:undefined,
      },
      list: null,
      listLoading: true,
      textMap: {
        update: '编辑表单',
        create: '新增表单'
      },
      dialogStatus:'',
      dialogFormVisible: false,
      uploadUrl:process.env.VUE_APP_BASE_API+'/admin/index/headUpload',
    }
  },
  created() {
    this.fetchData()
    // this.getAdmins()
  },
  methods: {
    //打开查看数据
    lookDataOpen(row){
      this.forms_id = row.forms_id
      this.lookDataTitle = row.forms_title
      this.lookDataStatus = true
    },
    //关闭查看数据
    lookDataCloseF(){
      this.lookDataStatus = false
      //this.forms_id = ""
    },
   createQr(link_url) {
      return new Promise((resolve, reject) => {
        QRCode.toDataURL(link_url, {
          version: 7,
          errorCorrectionLevel: 'Q',
          width: 280,
          height: 280,
        })
          .then(url => {
            resolve(url); // 返回生成的URL
          })
          .catch(err => {
            console.error(err);
            reject(err); // 发生错误时返回错误
          });
      });
    },
    getAdmins(){
      getAdmin().then((res) => {
        if(res.status==200){
          this.admin_data = res.data
        }
      })
    },
    //关闭弹窗的新增和修改
    dialogFormClose(){
      this.dialogFormVisible = false
      this.$refs.forms.removeForms();
      this.draggable = false//销毁组件
    },
    handleFilter() {
      this.listQuery.page = 1
      this.fetchData()
    },
    handleCreate() {
     //清空传参
      this.arr2 = []
      this.formDataItem2 = {}

      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.draggable = true//启用组件
    },
    //子页面点击保存后，触发接收子组件的操作
    handleData(data){
      if(data.type == 'create'){
        this.createData(data.forms)
      }else{
        this.updateData(data.forms)
      }
    },
    //新增操作方法
    createData(forms) {
      createForms(forms).then((res) => {
        if(res.status==200){
          this.$notify({
            title: 'Success',
            message: res.msg,
            type: 'success',
            duration: 2000
          })
          this.dialogFormVisible = false
          this.fetchData()
        }else{
          this.$notify({
            title: 'Error',
            message: res.msg,
            type: 'error',
            duration: 2000
          })
        }
      })
      this.draggable = false//销毁组件
    },
    //按钮唤起编辑
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.arr2 = this.temp.forms_content
      this.formDataItem2 = this.temp
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.draggable = true//启用组件
    },
    //编辑操作方法
    updateData(forms) {
      updateForms(forms).then((res) => {
        if(res.status==200){
          this.dialogFormVisible = false
          this.$notify({
            title: 'Success',
            message: res.msg,
            type: 'success',
            duration: 2000
          })
          this.fetchData()
        }else{
          this.$notify({
            title: 'Error',
            message: res.msg,
            type: 'error',
            duration: 2000
          })
        }
      })
      this.draggable = false//销毁组件
    },
    fetchData() {
      this.listLoading = true
      getForms(this.listQuery).then(response => {
        let old_list = response.data
        let newList = []
        for(let i=0;i<response.data.length;i++){
          let a = old_list[i]
          this.createQr(old_list[i].url).then((res)=>{
            a.url_img = res
            newList.push(a)
          })
        }
        this.list = newList
        this.total = response.total
        this.listLoading = false
      })
    },
    handleDelete(row, index) {
      this.$confirm('此操作将永久删除该id程序, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delForms({	forms_id:row.forms_id}).then(response => {
          // this.list = response.data.items
            if(response.status==200){
              this.$notify({
                  title: 'Success',
                  message: response.msg,
                  type: 'success',
                  duration: 2000
              })
              this.list.splice(index, 1)
          }else{
            this.$notify({
                  title: 'Error',
                  message: response.msg,
                  type: 'error',
                  duration: 2000
              })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleAllDelete(){
      this.$prompt('请输入此账号的密码', '提示', {
        inputType:'password',
        showInput:true,
        inputPlaceholder:'请输入此账号的密码',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern:/\S/,
        inputErrorMessage: '密码不为空'
      }).then(({ value }) => {
        delAllList({admin_password:value}).then(response=>{
          if(response.status==200){
            this.$notify({
              title: 'Success',
              message: response.msg,
              type: 'success',
              duration: 2000
            })
            this.fetchData()
          }else {
            this.$notify({
              title: 'Error',
              message: response.msg,
              type: 'error',
              duration: 2000
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        });
      });
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['ID', '姓名', '年龄', '手机', '时间']
        const filterVal = ['submit_id', 'submit_name', 'submit_ago', 'submit_phone', 'submit_time']
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.table_name
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },

  },
  components:{
    Pagination,
    Tinymce,
    draggableIndex3,
    appDataList
  }
}
</script>
